package com.xbongbong.paas.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.xbongbong.formula.constant.Constant;
import com.xbongbong.i18n.util.I18nMessageUtil;
import com.xbongbong.paas.constant.MessageConstant;
import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.enums.DelEnum;
import com.xbongbong.paas.log.MongoLogHelp;
import com.xbongbong.paas.log.constant.LogMemoConstant;
import com.xbongbong.paas.service.SystemLabelService;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.CollectionsUtil;
import com.xbongbong.paas.toolbox.util.DateTimeUtil;
import com.xbongbong.paas.toolbox.wrap.BaseDTO;
import com.xbongbong.paas.toolbox.wrap.BaseVO;
import com.xbongbong.paas.toolbox.wrap.UserVO;
import com.xbongbong.pro.domain.entity.SysLabelEntity;
import com.xbongbong.pro.enums.ErrorCodeEnum;
import com.xbongbong.pro.enums.errorcodes.SystemLabelErrorCodeEnum;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.pro.label.pojo.LabelGroupListPojo;
import com.xbongbong.pro.label.pojo.LabelPojo;
import com.xbongbong.pro.label.pojo.LabelSortPojo;
import com.xbongbong.pro.label.pojo.dto.LabelSortDTO;
import com.xbongbong.pro.label.pojo.vo.LabelGroupListVO;
import com.xbongbong.pro.label.pojo.vo.LabelSortVO;
import com.xbongbong.pro.model.SysLabelModel;
import com.xbongbong.pro.systemlabel.pojo.dto.SystemLabelAddBatchDTO;
import com.xbongbong.pro.systemlabel.pojo.dto.SystemLabelAddDTO;
import com.xbongbong.pro.systemlabel.pojo.dto.SystemLabelCompleteDeleteDTO;
import com.xbongbong.pro.systemlabel.pojo.dto.SystemLabelDeleteBatchDTO;
import com.xbongbong.pro.systemlabel.pojo.dto.SystemLabelDeleteDTO;
import com.xbongbong.pro.systemlabel.pojo.dto.SystemLabelListDTO;
import com.xbongbong.pro.systemlabel.pojo.dto.SystemLabelRecoverDTO;
import com.xbongbong.pro.systemlabel.pojo.dto.SystemLabelUpdateDTO;
import com.xbongbong.pro.systemlabel.pojo.vo.SystemLabelAddBatchVO;
import com.xbongbong.pro.systemlabel.pojo.vo.SystemLabelAddVO;
import com.xbongbong.pro.systemlabel.pojo.vo.SystemLabelCompleteDeleteVO;
import com.xbongbong.pro.systemlabel.pojo.vo.SystemLabelDeleteBatchVO;
import com.xbongbong.pro.systemlabel.pojo.vo.SystemLabelDeleteVO;
import com.xbongbong.pro.systemlabel.pojo.vo.SystemLabelListVO;
import com.xbongbong.pro.systemlabel.pojo.vo.SystemLabelPersonAddDTO;
import com.xbongbong.pro.systemlabel.pojo.vo.SystemLabelRecoverVO;
import com.xbongbong.pro.systemlabel.pojo.vo.SystemLabelUpdateVO;
import com.xbongbong.saas.constant.ParameterConstant;
import com.xbongbong.saas.constant.teammembers.TeamMembersConstant;
import com.xbongbong.saas.enums.OperateModuleTypeEnum;
import com.xbongbong.saas.enums.OperateTypeEnum;
import com.xbongbong.sys.domain.entity.UserEntity;
import com.xbongbong.sys.enums.SystemLabelGroupEnum;
import com.xbongbong.sys.model.UserModel;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 系统标签 service
 * @author 魏荣杰
 *
 */
@Service("systemLabelService")
@Slf4j
public class SystemLabelServiceImpl implements SystemLabelService {


    @Resource
    private SysLabelModel sysLabelModel;
    @Resource
    private UserModel userModel;
    @Resource
    private MongoLogHelp mongoLogHelp;

    @Override
    public SystemLabelAddVO add(SystemLabelAddDTO systemLabelAddDTO) throws XbbException {

        String corpid = systemLabelAddDTO.getCorpid();
        String name = systemLabelAddDTO.getName();
        UserVO loginUser = systemLabelAddDTO.getLoginUser();

        Map<String, Object> param  = new HashMap<>();
        param.put(ParameterConstant.CORPID, corpid);
        param.put("delIn", Arrays.asList(DelEnum.NORMAL.getDel(), DelEnum.DELETE.getDel()));
        param.put(ParameterConstant.NAME, name);
        List<SysLabelEntity> sysLabelEntities = sysLabelModel.findEntities(param);
        if (CollectionsUtil.isNotEmpty(sysLabelEntities)) {
            if (Objects.equals(sysLabelEntities.get(0).getDel(), DelEnum.NORMAL.getDel())) {
                throw new XbbException(SystemLabelErrorCodeEnum.API_ERROR_392001);
            } else {
                throw new XbbException(SystemLabelErrorCodeEnum.API_ERROR_392002);
            }
        }

        param.clear();
        param.put(ParameterConstant.CORPID, corpid);
        param.put(ParameterConstant.DEL, DelEnum.NORMAL.getDel());

//        Integer entityCount = sysLabelModel.getEntityCount(param);
        List<SysLabelEntity> sysLabelEntityList = sysLabelModel.findEntities(param);
        if (sysLabelEntityList.size() >= PaasConstant.LIMIT_MAX_NUM_SYSTEM_LABEL) {
            throw new XbbException(SystemLabelErrorCodeEnum.API_ERROR_1120012);
        }

        SysLabelEntity sysLabelEntity = new SysLabelEntity();
        sysLabelEntity.setCorpid(corpid);
        sysLabelEntity.setColor(systemLabelAddDTO.getColor());
        sysLabelEntity.setName(name);
        //新增的要排在最上面，因此sort要给最大
        List<Integer> sortList = sysLabelEntityList.stream().map(SysLabelEntity::getSort).collect(Collectors.toList());
        sysLabelEntity.setSort(CollectionUtils.isEmpty(sortList) ? Constant.ONE : Collections.max(sortList) + Constant.ONE);
        sysLabelEntity.setCreatorId(systemLabelAddDTO.getUserId());
        long now = DateTimeUtil.getInt();
        sysLabelEntity.setAddTime(now);
        sysLabelEntity.setUpdateTime(now);
        sysLabelEntity.setDel(DelEnum.NORMAL.getDel());

        sysLabelModel.insert(sysLabelEntity);


        //日志
        String memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_SYSTEM_LABEL_ADD),loginUser.getName(),systemLabelAddDTO.getName());
        mongoLogHelp.buildLog(corpid,loginUser.getUserId(),loginUser.getName(), OperateModuleTypeEnum.SYSTEM_LABEL, OperateTypeEnum.NEW,sysLabelEntity.getId().toString(),sysLabelEntity.getName(),memo,systemLabelAddDTO.getHttpHeader());
        SystemLabelAddVO systemLabelAddVO = new SystemLabelAddVO();
        systemLabelAddVO.setId(systemLabelAddVO.getId());
        return systemLabelAddVO;
    }

    @Override
    public SystemLabelUpdateVO update(SystemLabelUpdateDTO systemLabelUpdateDTO) throws XbbException {

        String corpid = systemLabelUpdateDTO.getCorpid();
        String name = systemLabelUpdateDTO.getName();
        UserVO loginUser = systemLabelUpdateDTO.getLoginUser();
        Long id = systemLabelUpdateDTO.getId();
        Map<String, Object> param  = new HashMap<>();
        param.put(ParameterConstant.CORPID, corpid);
        param.put("delIn", Arrays.asList(DelEnum.NORMAL.getDel(), DelEnum.DELETE.getDel()));
        param.put(ParameterConstant.NAME, name);
        param.put("idNot", id);
        List<SysLabelEntity> sysLabelEntities = sysLabelModel.findEntities(param);
        if (CollectionsUtil.isNotEmpty(sysLabelEntities)) {
            if (Objects.equals(sysLabelEntities.get(0).getDel(), DelEnum.NORMAL.getDel())) {
                throw new XbbException(SystemLabelErrorCodeEnum.API_ERROR_392001);
            } else {
                throw new XbbException(SystemLabelErrorCodeEnum.API_ERROR_392002);
            }
        }

        SysLabelEntity sysLabel = sysLabelModel.getByKey(id, corpid);
        if (Objects.isNull(sysLabel)) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100404);
        }
        sysLabel.setName(name);
        sysLabel.setColor(systemLabelUpdateDTO.getColor());
        sysLabel.setUpdateTime(DateTimeUtil.getInt());
        sysLabelModel.update(sysLabel);

        //日志
        String memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_SYSTEM_LABEL_EDIT),loginUser.getName(),systemLabelUpdateDTO.getName());
        mongoLogHelp.buildLog(corpid,loginUser.getUserId(),loginUser.getName(), OperateModuleTypeEnum.SYSTEM_LABEL, OperateTypeEnum.EDIT,sysLabel.getId().toString(),sysLabel.getName(),memo,systemLabelUpdateDTO.getHttpHeader());

        SystemLabelUpdateVO systemLabelUpdateVO = new SystemLabelUpdateVO();
        systemLabelUpdateVO.setId(sysLabel.getId());
        return systemLabelUpdateVO;
    }

    @Override
    public SystemLabelDeleteVO delete(SystemLabelDeleteDTO systemLabelDeleteDTO) throws XbbException {

        String corpid = systemLabelDeleteDTO.getCorpid();
        UserVO loginUser = systemLabelDeleteDTO.getLoginUser();
        List<Long> ids = systemLabelDeleteDTO.getIds();
        List<SysLabelEntity> sysLabelEntities = sysLabelModel.getByLabelIdIn(corpid, ids);
        if (Objects.isNull(sysLabelEntities)) {
            throw new XbbException(SystemLabelErrorCodeEnum.API_ERROR_1120019);
        }

        long now = DateTimeUtil.getInt();
        sysLabelEntities.forEach(v -> {
            v.setDel(DelEnum.DELETE.getDel());
            v.setUpdateTime(now);
        });
        sysLabelModel.updateBatch(sysLabelEntities, corpid);

        //日志
        String memo;
        ArrayList<String> labels = new ArrayList<>();
        sysLabelEntities.forEach(sysLabel ->
                labels.add(sysLabel.getName())
        );
        String labelNames = StringUtils.join(labels, "，");
        if(sysLabelEntities.size() == 1){
            memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_SYSTEM_LABEL_DEL),loginUser.getName(),labelNames);
            mongoLogHelp.buildLog(corpid,loginUser.getUserId(),loginUser.getName(), OperateModuleTypeEnum.SYSTEM_LABEL, OperateTypeEnum.TO_RECYCLE_BIN,sysLabelEntities.get(0).getId().toString(), sysLabelEntities.get(0).getName(), memo, systemLabelDeleteDTO.getHttpHeader());
        }else if(sysLabelEntities.size() > 1){
            memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_SYSTEM_LABEL_DEL_MATCH), loginUser.getName(), labelNames);
            mongoLogHelp.buildLog(corpid, loginUser.getUserId(), loginUser.getName(), OperateModuleTypeEnum.SYSTEM_LABEL, OperateTypeEnum.TO_RECYCLE_BIN,"", labelNames, memo, systemLabelDeleteDTO.getHttpHeader());
        }


        SystemLabelDeleteVO systemLabelDeleteVO = new SystemLabelDeleteVO();
        systemLabelDeleteVO.setIds(ids);
        return systemLabelDeleteVO;
    }

    @Override
    public SystemLabelAddBatchVO addBatch(SystemLabelAddBatchDTO systemLabelAddBatchDTO) throws XbbException {
        String corpid = systemLabelAddBatchDTO.getCorpid();
        List<String> userIdList = systemLabelAddBatchDTO.getUserIds();
        Long id = systemLabelAddBatchDTO.getId();
        UserVO loginUser = systemLabelAddBatchDTO.getLoginUser();
        List<UserEntity> userEntityList = userModel.getByUserIdIn(corpid, userIdList);
        SysLabelEntity sysLabel = sysLabelModel.getByKey(systemLabelAddBatchDTO.getId(),corpid);
        List<UserEntity> updateList = new ArrayList<>();
        for (UserEntity userEntity : userEntityList) {
            JSONArray labelArray = userEntity.getLabels();
            if (Objects.isNull(labelArray)) {
                labelArray = new JSONArray();
            }
            if (labelArray.size() >= TeamMembersConstant.USER_LABEL_LIMIT) {
                continue;
            }
            if(!labelArray.contains(id.intValue())){
                labelArray.add(id);
            }
            userEntity.setLabels(labelArray);
            updateList.add(userEntity);
        }

        if (CollectionsUtil.isNotEmpty(updateList)) {
            userModel.updateBatch(updateList, corpid);
        }

        //日志
        String memo;
        ArrayList<String> userNames = new ArrayList<>();
        updateList.forEach(user ->
                userNames.add(user.getName())
        );
        String userNameStr = StringUtils.join(userNames, "，");
        if(updateList.size() == 1){
            memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_SYSTEM_LABEL_ADD_USER),loginUser.getName(),userNameStr,sysLabel.getName());
            mongoLogHelp.buildLog(corpid,loginUser.getUserId(),loginUser.getName(), OperateModuleTypeEnum.SYSTEM_LABEL, OperateTypeEnum.ADD_LABEL,systemLabelAddBatchDTO.getId().toString(),sysLabel.getName(),memo,systemLabelAddBatchDTO.getHttpHeader());
        }else if(updateList.size() > 1){
            memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_SYSTEM_LABEL_ADD_USER_MATCH),loginUser.getName(),userNameStr,sysLabel.getName());
            mongoLogHelp.buildLog(corpid,loginUser.getUserId(),loginUser.getName(), OperateModuleTypeEnum.SYSTEM_LABEL, OperateTypeEnum.ADD_LABEL,systemLabelAddBatchDTO.getId().toString(),sysLabel.getName(),memo,systemLabelAddBatchDTO.getHttpHeader());
        }

        SystemLabelAddBatchVO systemLabelAddBatchVO = new SystemLabelAddBatchVO();
        return systemLabelAddBatchVO;
    }

    @Override
    public SystemLabelDeleteBatchVO deleteBatch(SystemLabelDeleteBatchDTO systemLabelDeleteBatchDTO) throws XbbException {

        Long id = systemLabelDeleteBatchDTO.getId();
        String corpid = systemLabelDeleteBatchDTO.getCorpid();
        List<String> userIdList = systemLabelDeleteBatchDTO.getUserIds();
        UserVO loginUser = systemLabelDeleteBatchDTO.getLoginUser();
        List<UserEntity> userEntities = userModel.getByUserIdIn(corpid, userIdList);
        SysLabelEntity sysLabel = sysLabelModel.getByKey(systemLabelDeleteBatchDTO.getId(),corpid);
        List<UserEntity> updateList = new ArrayList<>();
        for (UserEntity userEntity : userEntities) {
            JSONArray labelArray = userEntity.getLabels();
            if (Objects.isNull(labelArray)) {
                labelArray = new JSONArray();
            }
            labelArray.removeIf(v -> Objects.equals(Long.valueOf(v.toString()), id));
            userEntity.setLabels(labelArray);

            updateList.add(userEntity);
        }

        if (CollectionsUtil.isNotEmpty(updateList)) {
            userModel.updateBatch(updateList, corpid);
        }

        //日志
        String memo;
        ArrayList<String> userNames = new ArrayList<>();
        updateList.forEach(user ->
                userNames.add(user.getName())
        );
        String userNameStr = StringUtils.join(userNames, "，");
        if(updateList.size() == 1){
            memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_SYSTEM_LABEL_DEL_USER),loginUser.getName(),userNameStr,sysLabel.getName());
            mongoLogHelp.buildLog(corpid,loginUser.getUserId(),loginUser.getName(), OperateModuleTypeEnum.SYSTEM_LABEL, OperateTypeEnum.REMOVE_LABEL,systemLabelDeleteBatchDTO.getId().toString(),sysLabel.getName(),memo,systemLabelDeleteBatchDTO.getHttpHeader());
        }else if(updateList.size() > 1){
            memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_SYSTEM_LABEL_DEL_USER_MATCH),loginUser.getName(),userNameStr,sysLabel.getName());
            mongoLogHelp.buildLog(corpid,loginUser.getUserId(),loginUser.getName(), OperateModuleTypeEnum.SYSTEM_LABEL, OperateTypeEnum.REMOVE_LABEL,systemLabelDeleteBatchDTO.getId().toString(),sysLabel.getName(),memo,systemLabelDeleteBatchDTO.getHttpHeader());
        }

        SystemLabelDeleteBatchVO systemLabelDeleteBatchVO = new SystemLabelDeleteBatchVO();
        return systemLabelDeleteBatchVO;
    }


    @Override
    public SystemLabelListVO list(SystemLabelListDTO systemLabelListDTO) throws XbbException {
        String corpid = systemLabelListDTO.getCorpid();
        Long groupId = systemLabelListDTO.getGroupId();

        List<LabelPojo> labelListVO = new ArrayList<>();
        if (Objects.equals(groupId, SystemLabelGroupEnum.DEFAULT_GROUP.getId())) {
            // 默认分组
            Map<String, Object> param = new HashMap<>();
            param.put(ParameterConstant.CORPID, corpid);
            param.put(ParameterConstant.DEL, DelEnum.NORMAL.getDel());
            List<SysLabelEntity> sysLabelEntities = sysLabelModel.findEntities(param);
            sysLabelEntities.forEach(v -> labelListVO.add(new LabelPojo(v.getId(), v.getName(), v.getColor(), v.getSort())));
        } else {
            // 回收站
            Map<String, Object> param = new HashMap<>();
            param.put(ParameterConstant.CORPID, corpid);
            param.put(ParameterConstant.DEL, DelEnum.DELETE.getDel());
            List<SysLabelEntity> sysLabelEntities = sysLabelModel.findEntities(param);
            sysLabelEntities.forEach(v -> labelListVO.add(new LabelPojo(v.getId(), v.getName(), v.getColor(), v.getSort())));
        }

        SystemLabelListVO systemLabelListVO = new SystemLabelListVO();
        systemLabelListVO.setLabelListVO(labelListVO);

        return systemLabelListVO;
    }


    @Override
    public SystemLabelRecoverVO recover(SystemLabelRecoverDTO systemLabelRecoverDTO) throws XbbException {
        String corpid = systemLabelRecoverDTO.getCorpid();
        Long id = systemLabelRecoverDTO.getId();
        UserVO loginUser = systemLabelRecoverDTO.getLoginUser();
        Map<String, Object> param  = new HashMap<>();
        param.put(ParameterConstant.CORPID, corpid);
        param.put(ParameterConstant.DEL, DelEnum.NORMAL.getDel());
//        Integer entityCount = sysLabelModel.getEntityCount(param);
        List<SysLabelEntity> sysLabelEntityList = sysLabelModel.findEntities(param);
        if (sysLabelEntityList.size() >= PaasConstant.LIMIT_MAX_NUM_SYSTEM_LABEL) {
            throw new XbbException(SystemLabelErrorCodeEnum.API_ERROR_1120012);
        }
        SysLabelEntity sysLabelEntity = sysLabelModel.getByKey(id, corpid);
        if (Objects.isNull(sysLabelEntity)) {
            throw new XbbException(SystemLabelErrorCodeEnum.API_ERROR_1120019);
        }

        sysLabelEntity.setDel(DelEnum.NORMAL.getDel());
        sysLabelEntity.setUpdateTime(DateTimeUtil.getInt());
        //恢复的标签要展示在最上方
        List<Integer> sortList = sysLabelEntityList.stream().map(SysLabelEntity::getSort).collect(Collectors.toList());
        sysLabelEntity.setSort(CollectionUtils.isEmpty(sortList) ? Constant.ONE : Collections.max(sortList) + Constant.ONE);
        sysLabelModel.update(sysLabelEntity);

        //日志
        String memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_SYSTEM_LABEL_RECOVER),loginUser.getName(),sysLabelEntity.getName());
        mongoLogHelp.buildLog(corpid,loginUser.getUserId(),loginUser.getName(), OperateModuleTypeEnum.SYSTEM_LABEL, OperateTypeEnum.RECOVER_LABEL,systemLabelRecoverDTO.getId().toString(),sysLabelEntity.getName(),memo,systemLabelRecoverDTO.getHttpHeader());

        SystemLabelRecoverVO systemLabelRecoverVO = new SystemLabelRecoverVO();
        systemLabelRecoverVO.setId(sysLabelEntity.getId());
        return systemLabelRecoverVO;

    }

    @Override
    public SystemLabelCompleteDeleteVO completeDelete(SystemLabelCompleteDeleteDTO systemLabelCompleteDeleteDTO) throws XbbException {
        String corpid = systemLabelCompleteDeleteDTO.getCorpid();
        Long id = systemLabelCompleteDeleteDTO.getId();
        UserVO loginUser = systemLabelCompleteDeleteDTO.getLoginUser();
        SysLabelEntity sysLabelEntity = sysLabelModel.getByKey(id, corpid);
        if (Objects.isNull(sysLabelEntity)) {
            throw new XbbException(SystemLabelErrorCodeEnum.API_ERROR_1120019);
        }

        Map<String, Object> param = new HashMap<>();
        param.put(ParameterConstant.CORPID, corpid);
        param.put(ParameterConstant.DEL, DelEnum.NORMAL.getDel());
        param.put("labelId", id);

        Integer entitysCount = userModel.getEntitysCount(param);
        if (entitysCount > 0) {
            throw new XbbException(SystemLabelErrorCodeEnum.API_ERROR_1120024);
        }


        sysLabelEntity.setDel(DelEnum.APPROVE_STATUS.getDel());
        sysLabelEntity.setUpdateTime(DateTimeUtil.getInt());
        sysLabelModel.update(sysLabelEntity);

        //日志
        String memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_SYSTEM_LABEL_COMPLETE_DEL),loginUser.getName(),sysLabelEntity.getName());
        mongoLogHelp.buildLog(corpid,loginUser.getUserId(),loginUser.getName(), OperateModuleTypeEnum.SYSTEM_LABEL, OperateTypeEnum.DELETE,systemLabelCompleteDeleteDTO.getId().toString(),sysLabelEntity.getName(),memo,systemLabelCompleteDeleteDTO.getHttpHeader());

        SystemLabelCompleteDeleteVO systemLabelCompleteDeleteVO = new SystemLabelCompleteDeleteVO();
        systemLabelCompleteDeleteVO.setId(sysLabelEntity.getId());
        return systemLabelCompleteDeleteVO;
    }

    @Override
    public LabelSortVO sort(LabelSortDTO labelSortDTO) throws XbbException {
        String corpid = labelSortDTO.getCorpid();
        List<LabelSortPojo> sortArray = labelSortDTO.getSortArray();

        List<Long> ids = new ArrayList<>();
        Map<Long, Integer> sortMap = new HashMap<>();
        sortArray.forEach(v -> {
            ids.add(v.getId());
            sortMap.put(v.getId(), v.getSort().intValue());
        });

        Map<String, Object> param = new HashMap<>();
        param.put(ParameterConstant.CORPID, corpid);
        param.put("idIn", ids);
        List<SysLabelEntity> sysLabelEntities = sysLabelModel.findEntities(param);

        long now = DateTimeUtil.getInt();
        sysLabelEntities.forEach(v -> {
            v.setSort(sortMap.get(v.getId()));
            v.setUpdateTime(now);
        });

        sysLabelModel.updateBatch(sysLabelEntities, corpid);

        LabelSortVO labelSortVO = new LabelSortVO();
        labelSortVO.setIds(ids);
        return labelSortVO;
    }

    @Override
    public LabelGroupListVO groupList(BaseDTO baseDTO) throws XbbException {

        List<LabelGroupListPojo> labelTree = new ArrayList<>();


        for (SystemLabelGroupEnum value : SystemLabelGroupEnum.values()) {
            LabelGroupListPojo labelGroupListPojo = new LabelGroupListPojo();
            labelGroupListPojo.setId(value.getId());
            labelGroupListPojo.setName(value.getName());
            labelGroupListPojo.setSort(value.getSort());
            labelTree.add(labelGroupListPojo);
        }

        LabelGroupListVO labelGroupListVO = new LabelGroupListVO();
        labelGroupListVO.setLabelTree(labelTree);
        return labelGroupListVO;

    }

    @Override
    public SystemLabelListVO sampleList(BaseDTO baseDTO) throws XbbException {
        String corpid = baseDTO.getCorpid();

        Map<String, Object> param = new HashMap<>();
        param.put(ParameterConstant.CORPID, corpid);
        param.put(ParameterConstant.DEL, DelEnum.NORMAL.getDel());

        List<SysLabelEntity> sysLabelEntities = sysLabelModel.findEntities(param);


        List<LabelPojo> labelListVO = new ArrayList<>();
        sysLabelEntities.forEach(v -> labelListVO.add(new LabelPojo(v.getId(), v.getColor(), v.getName())));

        SystemLabelListVO systemLabelListVO = new SystemLabelListVO();
        systemLabelListVO.setLabelListVO(labelListVO);
        return systemLabelListVO;

    }

    @Override
    public BaseVO personAdd(SystemLabelPersonAddDTO systemLabelPersonAddDTO) throws XbbException {

        String corpid = systemLabelPersonAddDTO.getCorpid();
        String personId = systemLabelPersonAddDTO.getPersonId();
        List<Long> labels = systemLabelPersonAddDTO.getLabels();
        UserVO loginUser = systemLabelPersonAddDTO.getLoginUser();
        List<SysLabelEntity> byLabelIdIn = sysLabelModel.getByLabelIdIn(corpid, labels);
        UserEntity userEntity = userModel.getByKey(personId, corpid);
        if (Objects.isNull(userEntity)) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.USER_NOT_EXIST);
        }

        Set<Long> labelSet = new HashSet<>(labels);
        if (labelSet.size() > TeamMembersConstant.USER_LABEL_LIMIT) {
            throw new XbbException(SystemLabelErrorCodeEnum.API_ERROR_1120012);
        }
        userEntity.setLabels(JSON.parseArray(JSON.toJSONString(labelSet)));
        userModel.update(userEntity);

        //日志
        String memo;
        ArrayList<String> labelNameList = new ArrayList<>();
        byLabelIdIn.forEach(user ->
                labelNameList.add(user.getName())
        );
        String userNameStr = StringUtils.join(labelNameList, "，");
        if(byLabelIdIn.size() == 1){
            memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_SYSTEM_LABEL_ADD_PERSON),loginUser.getName(),userEntity.getName(),userNameStr);
            mongoLogHelp.buildLog(corpid,loginUser.getUserId(),loginUser.getName(), OperateModuleTypeEnum.SYSTEM_LABEL, OperateTypeEnum.EDIT_LABEL,personId,userEntity.getName(),memo,systemLabelPersonAddDTO.getHttpHeader());
        }else if(byLabelIdIn.size() > 1){
            memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_SYSTEM_LABEL_ADD_PERSON_MATCH),loginUser.getName(),userEntity.getName(),userNameStr);
            mongoLogHelp.buildLog(corpid,loginUser.getUserId(),loginUser.getName(), OperateModuleTypeEnum.SYSTEM_LABEL, OperateTypeEnum.EDIT_LABEL,personId,userEntity.getName(),memo,systemLabelPersonAddDTO.getHttpHeader());

        }


        return new BaseVO();
    }

}
